package com.source.hotelbath.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.source.hotelbath.MainActivity;
import com.source.hotelbath.R;
import com.source.hotelbath.base.BizActivity;
import com.source.hotelbath.model.OrderGoodsList;
import com.source.hotelbath.model.PostBean;
import com.source.hotelbath.net.CustomerRequestConstants;
import com.source.hotelbath.net.response.OrderSubmitResponse;
import com.source.hotelbath.utils.DialogCallback;
import com.source.hotelbath.utils.SharedPreferencesUtils;
import com.source.hotelbath.utils.ToolsUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.weipass.pos.sdk.IPrint;
import cn.weipass.pos.sdk.LatticePrinter;
import cn.weipass.pos.sdk.Printer;
import cn.weipass.pos.sdk.impl.WeiposImpl;

public class CreateOrderActivity extends BizActivity {


    private ListView lv_for;
    private TextView tv_hotel;
    private TextView tv_person;
    private TextView tv_phone;
    private TextView tv_remek;
    private Button btn_change;
    private Button btn_submit;
    private LinearLayout ll_header_left;
    private LinearLayout ll_header_right;
    private OrderGoodsList goodsList;
    private List<PostBean> orderGoodsList=new ArrayList<>();
    private CreateOrderAdapter orderAdapter;
    public static String path= Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qm.png";
    private String order;
    private ImageView iv_sign;
    private Button btn_sign;
    private String totle;
    private int sums;
    private Printer printer = null;//普通打印对象
    private LinearLayout ll_sign;

    @Override
    protected void onBaseCreate(Bundle var1) {
        setContentView(R.layout.activity_create_order);
    }

    @Override
    protected void bindView(Bundle var1) {
        goodsList = getIntent().getParcelableExtra("goodsList");
        totle = getIntent().getStringExtra("tv_money");
        sums = getIntent().getIntExtra("sums",0);


        ll_header_left = (LinearLayout) findViewById(R.id.ll_header_left);
        ll_header_right = (LinearLayout) findViewById(R.id.ll_header_right);
        ll_header_right.setVisibility(View.GONE);
        ll_header_left.setOnClickListener(this);
        TextView tv_header_title= (TextView) findViewById(R.id.tv_header_title);
        tv_header_title.setText("取布草");
        lv_for = (ListView) findViewById(R.id.lv_for);
        tv_hotel = (TextView) findViewById(R.id.tv_hotel);
        tv_person = (TextView) findViewById(R.id.tv_person);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_remek = (TextView) findViewById(R.id.tv_remek);
        iv_sign = (ImageView) findViewById(R.id.iv_sign);
        btn_sign = (Button) findViewById(R.id.btn_sign);
        ll_sign = (LinearLayout) findViewById(R.id.ll_sign);
        btn_sign.setVisibility(View.GONE);
        ll_sign.setVisibility(View.GONE);
        if (null!=goodsList){
            order = new Gson().toJson(goodsList);
            orderGoodsList.addAll(goodsList.getOrderGoodsList());
            Log.d("orderGoodsList",orderGoodsList.size()+"==");
            tv_hotel.setText("酒店名称："+goodsList.getHotelName());
            tv_remek.setText("备注信息："+goodsList.getRemark());
        }else {
            tv_hotel.setText("酒店名称：");
            tv_remek.setText("备注信息：");
        }


        tv_person.setText("操作人员："+ SharedPreferencesUtils.getStringData(this,"name",""));
        tv_phone.setText("联系电话："+ SharedPreferencesUtils.getStringData(this,"phone",""));

        btn_change = (Button) findViewById(R.id.btn_change);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        btn_change.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
        btn_sign.setOnClickListener(this);
        orderAdapter = new CreateOrderAdapter(this,orderGoodsList, totle, sums);

        lv_for.setAdapter(orderAdapter);
        try {
            // 设备可能没有打印机，open会抛异常
            latticePrinter = WeiposImpl.as().openLatticePrinter();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }

    private LatticePrinter latticePrinter;// 点阵打印
    private int click;

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view==ll_header_left){
            finish();
        }else if(view==btn_change){
            finish();
        }else if (view==btn_submit){
            startActivityForResult(new Intent(CreateOrderActivity.this, SignActivity.class), 1);
        }else if (view==btn_sign){
            click+=1;
            btn_sign.setText("打印小票第2次");
            //点阵打印
            if (latticePrinter == null) {
                Toast.makeText(CreateOrderActivity.this, "尚未初始化点阵打印sdk，请稍后再试", Toast.LENGTH_SHORT).show();
                return;
            }
            // 打印内容赋值
            latticePrinter.setOnEventListener(new IPrint.OnEventListener() {

                @Override
                public void onEvent(final int what, String in) {
                    // TODO Auto-generated method stub
                    final String info = in;
                    // 回调函数中不能做UI操作，所以可以使用runOnUiThread函数来包装一下代码块
                    runOnUiThread(new Runnable() {
                        public void run() {
                            final String message = ToolsUtil.getPrintErrorInfo(what, info);
                            if (message == null || message.length() < 1) {
                                return;
                            }
                            showResultInfo("打印", "打印结果信息", message);
                        }
                    });
                }
            });
            ToolsUtil.printLattice(CreateOrderActivity.this, latticePrinter,goodsList,goodsList.getHotelName(),goodsList.getRemark(),totle,sums);
            if (click==2){
                btn_sign.setClickable(false);
                btn_sign.setText("打印结束");
                btn_sign.setBackgroundResource(R.drawable.grey_btn);
            }

//            Intent intent = new Intent(CreateOrderActivity.this, MainActivity.class);
//            intent.putExtra("success",true);
//            startActivity(intent);
        }
    }

    private void showResultInfo(String operInfo, String titleHeader, String info) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setMessage(titleHeader + ":" + info);
        builder.setTitle(operInfo);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==100)
        {//请求网络提交订单
            OkGo.<OrderSubmitResponse>post(CustomerRequestConstants.newUrl+CustomerRequestConstants.ORDER_SUBMIT_COMMOND)//
                    .tag(this)//
                .params("sign",new File(path))   //这种方式为一个key，对应一个文件
                    .params("order",order)
//                .params("file2",new File("文件路径"))
//                .params("file3",new File("文件路径"))
                    // 这种方式为同一个key，上传多个文件
                    .execute(new DialogCallback<OrderSubmitResponse>(CreateOrderActivity.this,true) {
                        @Override
                        public void onSuccess(Response<OrderSubmitResponse> response) {
                            OrderSubmitResponse submitResponse=response.body();
                            if (submitResponse!=null){
                                if (submitResponse.isSuccess()){
                                    Intent intents = new Intent(CustomerRequestConstants.CHOOSEGOODS);
                                    intents.putExtra("isClear",true);
                                    LocalBroadcastManager.getInstance(CreateOrderActivity.this).sendBroadcast(intents);

                                    btn_change.setVisibility(View.GONE);
                                    btn_submit.setVisibility(View.GONE);
                                    btn_sign.setVisibility(View.VISIBLE);

                                    ll_sign.setVisibility(View.VISIBLE);
                                    BitmapFactory.Options options = new BitmapFactory.Options();
                                    options.inSampleSize = 2;
                                    Bitmap bm = BitmapFactory.decodeFile(path, options);
                                    iv_sign.setImageBitmap(bm);
                                }else {
                                    Toast.makeText(CreateOrderActivity.this,"提交失败",Toast.LENGTH_SHORT).show();
                                }

                            }
                        }

                        @Override
                        public void onError(Response<OrderSubmitResponse> response) {
                            super.onError(response);
                            Toast.makeText(CreateOrderActivity.this,"提交失败",Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
}
